//
//  LoginController.m
//  CMYH
//
//  Created by Loki on 15-5-13.
//  Copyright (c) 2015年 Loki. All rights reserved.
//

#import "LoginController.h"

#import "Define.h"
#import "Busi.h"


const NSInteger MSG_ENTERSERVERADDRESS                  = 1;


@interface LoginController () <BusiDelegate>
@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([XApp isiDevice4]) {
        CGRect rc = _labIPAddressTitle.frame;
        rc.origin.y -= 88;
        _labIPAddressTitle.frame = rc;
        
        rc = _labIPAddress.frame;
        rc.origin.y -= 88;
        _labIPAddress.frame = rc;
        
        rc = _labVersionHead.frame;
        rc.origin.y -= 88;
        _labVersionHead.frame = rc;
        
        rc = _labVersion.frame;
        rc.origin.y -= 88;
        _labVersion.frame = rc;
    }
    
    // 填充版本號
    _labVersion.text = [XApp appVersion];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // IP 地址
    NSString *strVal = [XUser stringForKey:kServerAddress];
    if ([strVal length] > 0) {
        [_labIPAddress setText:strVal];
    }
    
    // User ID
    strVal = [XUser userID];
    if ([strVal length] > 0) {
        [_txtUser setText:strVal];
    }
    
    // User Password
    strVal = [XUser userPwd];
    if ([strVal length] > 0) {
        [_txtPwd setText:strVal];
    }
    
    // 没有配置IP
    if (_labIPAddress.text.length == 0) {
        [XMsg showMessage:@"服務器IP地址尚未配置！请先进行配置！" withTitle:@"溫馨提示" tag:MSG_ENTERSERVERADDRESS delegate:self];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)onLogin:(id)sender {
    // [self performSegueWithIdentifier:@"gotoScan" sender:self];
    // return;
    if (_txtUser.text.length == 0) {
        // 校验用户名
        [XMsg showToast:@"請輸入用戶名！" withGravity:AlignTop andDuration:DurationNormal];
        [_txtUser becomeFirstResponder];
    }
    else if (_txtPwd.text.length == 0) {
        // 校验密码
        [XMsg showToast:@"請輸入用戶密碼！" withGravity:AlignTop andDuration:DurationNormal];
        [_txtPwd becomeFirstResponder];
    }
    else {
        // 登录
        [self login];
    }
}


- (void)onBackgroundTouch {
    [_txtUser resignFirstResponder];
    [_txtPwd resignFirstResponder];
}


/**
 * 服务器没有配置的消息框处理
 */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == MSG_ENTERSERVERADDRESS) {
        // 服务器IP配置提示
        if (buttonIndex == 0) {
            // 进行服务器IP配置
            [self performSegueWithIdentifier:@"gotoSetting" sender:self];
        }
    }
}


/**
 * 登录处理
 * @return
 */
- (void)login {
    // 显示等待
    [XMsg showProgress];
    
    // 处理登录
    Busi *req = [[Busi alloc] init];
    req.delegete = self;
    req.method = @"CheckLogin";
    [req addParam:_txtUser.text forKey:@"userName"];
    [req addParam:_txtPwd.text forKey:@"passWord"];
    [req query];
}


/**
 * 登录处理
 * @return
 */
- (void)getDriverInfo {
    // 显示等待
    [XMsg showProgress];
    
    // 获取司机名称
    NSString *strDriver = [XUser userName];
    
    // 处理登录
    Busi *req = [[Busi alloc] init];
    req.delegete = self;
    req.method = @"GetDriverInfoByName";
    [req addParam:strDriver forKey:@"driverName"];
    [req query];
}


/**
 * 处理登录数据
 * @param   res, 接收到的数据
 * @return
 */
- (void)disposeLogin:(NSDictionary*)res {
    if (res == nil) {
        return;
    }
    
    bool bRet = false;
    do {
        NSDictionary *dicEnvelope = [res objectForKey:@"soap:Envelope"];
        if (dicEnvelope == nil) {
            break;
        }
        
        NSDictionary *dicBody = [dicEnvelope objectForKey:@"soap:Body"];
        if (dicBody == nil) {
            break;
        }
        
        NSDictionary *dicResponse = [dicBody objectForKey:@"CheckLoginResponse"];
        if (dicResponse == nil) {
            break;
        }
        
        NSDictionary *dicResult = [dicResponse objectForKey:@"CheckLoginResult"];
        if (dicResult == nil) {
            break;
        }
        
        NSString *strUserName = [[dicResult objectForKey:@"UserName"] objectForKey:kValue];
        NSString *strPassword = [[dicResult objectForKey:@"Password1"] objectForKey:kValue];
        NSString *strAuthrity = [[dicResult objectForKey:@"Authority"] objectForKey:kValue];
        if (strUserName == nil || strPassword == nil || strAuthrity == nil) {
            break;
        }
        
        bRet = true;        // 登录成功
        [XUser setUserName:(NSString *) strUserName];
        [XUser setAuthority:(NSString *) strAuthrity];
        
        // 司机
        if ([strAuthrity isEqualToString:@"driver"]) {
            // 获取司机信息
            [self getDriverInfo];
        }
        else {
            // 登录成功，但是所在用户组不允许使用
            [XMsg showToast:@"對不起！您所在的用戶組不允許登錄本系統！" withGravity:AlignTop andDuration:DurationNormal];
        }
    } while (0);
    
    // 登陆失败
    if (!bRet) {
        [XMsg showToast:@"登錄失敗！請檢查您的用戶名和密碼！" withGravity:AlignTop andDuration:DurationNormal];
    }
}


/**
 * 处理司机信息数据
 * @param   res, 接收到的数据
 * @return
 */
- (void)disposeDriverInfo:(NSDictionary*)res {
    if (res == nil) {
        return;
    }
    
    bool bRet = false;
    do {
        NSDictionary *dicEnvelope = [res objectForKey:@"soap:Envelope"];
        if (dicEnvelope == nil) {
            break;
        }
        
        NSDictionary *dicBody = [dicEnvelope objectForKey:@"soap:Body"];
        if (dicBody == nil) {
            break;
        }
        
        NSDictionary *dicResponse = [dicBody objectForKey:@"GetDriverInfoByNameResponse"];
        if (dicResponse == nil) {
            break;
        }
        
        NSDictionary *dicResult = [dicResponse objectForKey:@"GetDriverInfoByNameResult"];
        if (dicResult == nil) {
            break;
        }
        
        NSString *strTruckNo = [[dicResult objectForKey:@"TruckNo"] objectForKey:kValue];
        NSString *strDriverName = [[dicResult objectForKey:@"DriverName"] objectForKey:kValue];
        NSString *strCapacity = [[dicResult objectForKey:@"Capacity"] objectForKey:kValue];
        if (strTruckNo == nil || strDriverName == nil || strCapacity == nil) {
            break;
        }
        
        bRet = true;        // 司机信息获取成功
        [XUser setUserID:_txtUser.text];
        [XUser setUserPwd:_txtPwd.text];
        [XUser setString:strTruckNo forKey:@"TruckNo"];
        [XUser setString:strDriverName forKey:@"DriverName"];
        [XUser setString:strCapacity forKey:@"Capacity"];
        
        // 跳转到扫描界面
        [self performSegueWithIdentifier:@"gotoScan" sender:self];
    } while (0);
    
    // 登陆失败
    if (!bRet) {
        [XMsg showToast:@"沒有該司機的相關信息！請您與管理員聯繫！" withGravity:AlignTop andDuration:DurationNormal];
    }
}


#pragma mark BusiDelegate
- (void)requestException:(NSException *)exception withID:(NSString *)reqID {
    if ([reqID isEqualToString:@"CheckLogin"]) {
        // 当前地址不可用，继续尝试下一个地址
        [XMsg hideProgress];
        [XMsg showToast:@"登錄失敗，服務器地址！"
            withGravity:AlignTop
            andDuration:DurationNormal];
        
        [self performSegueWithIdentifier:@"gotoSetting" sender:self];
    }
    else if ([reqID isEqualToString:@"GetDriverInfoByName"]) {
        // 隐藏等待
        [XMsg hideProgress];
        // 显示异常提示
        [XMsg showToast:[NSString stringWithFormat:@"無法獲取司機：%@的相關信息，錯誤原因：%@，請與管理員聯繫！", [exception reason], [XUser userName]]
            withGravity:AlignTop
            andDuration:DurationNormal];
    }
}


- (void)requestFinished:(NSObject *)res withHeaders:(NSDictionary *)headers andID:(NSString *)reqID {
    if ([reqID isEqualToString:@"CheckLogin"]) {
        // 登录检测
        [XMsg hideProgress];
        
        // 处理登录
        [self disposeLogin:(NSDictionary*) res];
    }
    else if ([reqID isEqualToString:@"GetDriverInfoByName"]) {
        // 获取司机信息
        [XMsg hideProgress];
        
        // 处理司机信息
        [self disposeDriverInfo:(NSDictionary*) res];
    }
}


@end
